import { Button, Space } from 'ant-design-vue'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { marketingApi } from '@/apis'
import type { GroupManageItem } from '@/apis/marketingTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { bus } from '@/utils'

import { groupManageStatusMap, groupManageStatusOptions } from '../constants'

export default defineComponent({
  name: 'GroupManage',
  setup() {
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        align: 'center',
        border: true,
        toolbarConfig: {
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '活动名称',
              field: 'name',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入'
                }
              }
            },
            {
              title: '活动状态',
              field: 'status',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                options: groupManageStatusOptions,
                props: {
                  placeholder: '请选择'
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100
        },
        columns: [
          {
            title: '活动名称',
            field: 'name'
          },
          {
            title: '活动ID',
            field: 'id'
          },
          {
            title: '成团数',
            field: 'groupNum'
          },
          {
            title: '参团人数',
            field: 'groupPeopleNum'
          },
          {
            title: '开始时间',
            field: 'activityStartTime',
            minWidth: 140,
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '结束时间',
            field: 'activityEndTime',
            minWidth: 140,
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '拼团券码',
            field: 'couponName'
          },
          {
            title: '券码下发量',
            field: 'sendNum'
          },
          {
            title: '状态',
            field: 'status',

            formatter: ({ cellValue }) => {
              if (cellValue === 0) {
                return '-'
              }
              return groupManageStatusMap[cellValue]
            }
          },
          {
            title: '操作',
            fixed: 'right',
            width: 230,
            slots: {
              default: 'operation'
            }
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await marketingApi.getGroupManageList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    const router = useRouter()
    const { showConfirm } = useDialog()

    /** 新建 */
    function handleCreate() {
      router.push({
        name: 'GroupCreate'
      })
    }

    /** 编辑 */
    function handleEdit(item: GroupManageItem) {
      const query = {
        id: item.id
      }

      if (item.status === 2) {
        Object.assign(query, { pending: true })
      }

      router.push({
        name: 'GroupEdit',
        query
      })
    }

    /** 查看 */
    function handleView(item: GroupManageItem) {
      router.push({
        name: 'GroupView',
        query: {
          id: item.id
        }
      })
    }

    /** 发布 */
    function handlePublish(item: GroupManageItem) {
      showConfirm({
        content: '确认发布？',
        onOk: async () => {
          await tableRef.value.refresh(async () => {
            await marketingApi.publishGroupMangeItem(item.id)
          })
        }
      })
    }

    /** 下架 */
    function handleFinish(item: GroupManageItem) {
      showConfirm({
        content: '确认下架？',
        onOk: async () => {
          await tableRef.value.refresh(async () => {
            await marketingApi.rackGroupManageItem(item.id)
          })
        }
      })
    }

    /** 复制 */
    async function handleCopy(item: GroupManageItem) {
      showConfirm({
        content: '确认复制？',
        onOk: async () => {
          await tableRef.value.refresh(async () => {
            await marketingApi.cloneGroupManageItem(item.id)
          })
        }
      })
    }

    onMounted(() => {
      bus.on('refreshGroupManageList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })

    return {
      tableRef,
      tableConfig,
      handleCreate,
      handleEdit,
      handleView,
      handlePublish,
      handleFinish,
      handleCopy
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            toolbarButtons: () => (
              <Space>
                <Button type="primary" onClick={this.handleCreate}>
                  新建
                </Button>
              </Space>
            ),
            operation: ({ row }: { row: GroupManageItem }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                  disabled={row.status === 3}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleView(row)}
                >
                  详情
                </Button>
                {row.isPublish ? (
                  <Button
                    type="link"
                    size="small"
                    onClick={() => this.handleFinish(row)}
                    disabled={row.status === 3}
                  >
                    下架
                  </Button>
                ) : (
                  <Button
                    type="link"
                    size="small"
                    onClick={() => this.handlePublish(row)}
                  >
                    发布
                  </Button>
                )}
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleCopy(row)}
                >
                  复制
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
